/**   
 * Copyright © 2016 北京之洲科技有限责任公司. All rights reserved.
 * 
 * @Title: CrawlBusinessOfAutoHome.java 
 * @Prject: carfactory
 * @Package: com.zizo.autohome.business.crawl 
 * @Description: 
 * @author: Alexis  
 * @email heyan0227@outlook.com
 * @date: 2016年8月11日 上午10:13:39 
 * @version: V1.0   
 */
package com.zizo.autohome.business.crawl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.zizo.autohome.business.bean.AutoHomeBusiness;
import com.zizo.autohome.business.dao.BusinessDaoOfAutoHome;
import com.zizo.core.Crawl;
import com.zizo.core.DAO;
import com.zizo.util.DocUtil;
import com.zizo.util.Util;

/**
 * @ClassName: CrawlBusinessOfAutoHome
 * @Description:
 * @author: Alexis
 * @date: 2016年8月11日 上午10:13:39
 */
public class BusinessCrawlOfAutoHome extends Crawl {

	private BusinessDaoOfAutoHome businessdao = (BusinessDaoOfAutoHome) dao;

	/**
	 * @Title:CrawlBusinessOfAutoHome
	 * @Description:
	 * @param id
	 * @param dao
	 */
	public BusinessCrawlOfAutoHome(String id, DAO dao) {
		super(id, dao);
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non Javadoc)
	 * 
	 * @Title: getPages
	 * 
	 * @Description:
	 * 
	 * @param doc
	 * 
	 * @param selectStr
	 * 
	 * @return
	 * 
	 * @see com.zizo.core.CrawlInterface#getPages(org.jsoup.nodes.Document,
	 * java.lang.String)
	 */
	@Override
	public int getPages(Document doc, String selectStr) {
		// selectStr="span.page-item-info"
		return Integer.parseInt(Util.getMatched(doc.select(selectStr).first().text(), "(共)(\\d{1,})(页)").group(2));
	}

	/*
	 * (non Javadoc)
	 * 
	 * @Title: getItems
	 * 
	 * @Description:
	 * 
	 * @param url
	 * 
	 * @see com.zizo.core.CrawlInterface#getItems(java.lang.String)
	 */
	@Override
	public void getItems(String url) {
		// url = http://dealer.autohome.com.cn/china/0_0_0_0_1_1_0.html;//授权经销商
		// url = http://dealer.autohome.com.cn/china/0_0_0_0_1_2_0.html;//综合经销商
		Document doc = DocUtil.getDoc(url);
		Elements items = doc.select("div.dealer-cont");
		for (Element item : items) {
			Element linkA = item.select("dl.dealer-cont-main a").first();
			String link = "http://dealer.autohome.com.cn" + linkA.attr("href");
			try {
				crawlContent(link);
			} catch (Exception e) {
				System.out.println(link);
			}
		}
	}

	/*
	 * (non Javadoc)
	 * 
	 * @Title: crawlContent
	 * 
	 * @Description:
	 * 
	 * @param url
	 * 
	 * @see com.zizo.core.CrawlInterface#crawlContent(java.lang.String)
	 */
	@Override
	public void crawlContent(String url) {
		try {
			Document doc = DocUtil.getDoc(url);
			Element js = doc.select("script").get(6);
			if (!js.html().contains("var dealerlist")) {
				js = doc.select("script").get(5);
			}
			String json = js.html();
//			System.out.println(json);
			JSONObject jsonObj = null;
			int dealerId = 0;// 经销商ID
			String phone = "";// 经销商电话
			String ministieName = "";// 经销商名称
			String address = "";// 经销商地址
			short hasAuth = 0;// 是否认证，含有营业执照
			String cityName = "";// 经销商所在城市的名称
			double mapLonBaidu = 0;// 纬度
			double mapLatBaidu = 0;// 经度
			String mainBand = "";// 主营品牌
			Map<Integer, Integer> cars = new HashMap<>();// 经销的品牌汽车ID，key=第二分类
			try {
				jsonObj = new JSONObject(Util.getMatched(json, "(var dealerlist=\\[)(.*)(\\];)").group(2));
				@SuppressWarnings("unchecked")
				Iterator<String> iterator = jsonObj.keys();
				String key = null;
				String value = null;
				while (iterator.hasNext()) {
					key = (String) iterator.next();
					if (key.equalsIgnoreCase("Icon")) {
						continue;
					}
					value = jsonObj.getString(key);
					switch (key) {
					case "Address":
						address = value;
						break;
					case "Phone":
						phone = value;
						break;
					case "DealerId":
						dealerId = Integer.parseInt(value);
						break;
					case "MinistieName":
						ministieName = value;
						break;
					case "HasAuth":
						int temp = value.equals("true") ? 1 : 0;
						hasAuth = (short) temp;
						break;
					case "CityName":
						cityName = value;
						break;
					case "MapLonBaidu":
						mapLonBaidu = Double.parseDouble(value);
						break;
					case "MapLatBaidu":
						mapLatBaidu = Double.parseDouble(value);
						break;
					case "MainBand":
						mainBand = value;
						break;
					default:
						break;
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Elements carlists = doc.select("div.brandtree-cont dl.tree-dl");
			for (Element carlist : carlists) {
				Element dt = carlist.select("dt a").first();
				String firstID = dt.attr("href").split("_")[1].split("\\.html")[0];
				Elements dd = carlist.select("dd a");
				for (Element car : dd) {
					String carid = car.attr("href").split("_")[1].split("\\.html")[0];
					cars.put(Integer.parseInt(carid), Integer.parseInt(firstID));
				}
			}
			AutoHomeBusiness business = new AutoHomeBusiness(dealerId, phone, ministieName, address, hasAuth, cityName,
					mapLonBaidu, mapLatBaidu, mainBand, cars);
			businessdao.insertData(business);
		} catch (Exception e) {
			System.out.println(url);
			e.printStackTrace();
		}
	}

	/*
	 * (non Javadoc)
	 * 
	 * @Title: run
	 * 
	 * @Description:
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		getItems("http://dealer.autohome.com.cn/china/0_0_0_0_" + this.id + "_2_0.html");
		System.out.println(this.id);
	}

//	public static void main(String[] args) throws Exception {
//		Connection currConn = ConnectionPool.getConnection("autohome_other", "server.so.car", "3308");
//		BusinessDaoOfAutoHome dao = new BusinessDaoOfAutoHome(currConn);
//		BusinessCrawlOfAutoHome crawl = new BusinessCrawlOfAutoHome("", dao);
//		crawl.crawlContent("http://dealer.autohome.com.cn/2018949/?pvareaid=103707");
//	}
}
